﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LaxCraft.Domain;
using LaxCraft.Helpers;
using LaxCraft.Repositories;

namespace LaxCraft.Attributes
{
    public class PlayerAuthorizeAttribute : AuthorizeAttribute
    {

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // first look at routedata then at request parameter:
            var idString = (httpContext.Request.RequestContext.RouteData.Values["id"] as string)
                     ??
                     (httpContext.Request["id"] as string);

            try
            {
                var id = int.Parse(idString);
                var user = (User)HttpContext.Current.Session["CurrentUser"];
                return user.IsAdministrator || user.Player.Id == id;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}